<!-- 播客主页/关注列表 -->
<template>
    <div class="common-layout">
        <span class="friend-list-title">
            关注列表
        </span>
        <div class="search-layout">
            <el-input placeholder="请输入用户名以在全部用户中查找博主" v-model="searchInputValue" class="input-with-search">
                <template #prepend>
                    <el-button :icon="Search"></el-button>
                </template>
                <template #append>
                    <el-button type="primary" style="background-color:  #107CE9;color: white;"
                        @click="getUserbyUsername">搜索</el-button>
                </template>
            </el-input>
        </div>
        <!-- 关注用户列表 -->
        <el-scrollbar v-if="listStatus" height="80%">
            <div class="userinfo" v-for="item in FriendListData" :key="item.useridAtten">
                <div>
                    <el-avatar :size="50" :src="item.userAvater" />
                    <div class="username-email">
                        <el-text class="fullWid username">
                            {{ item.username }}
                        </el-text>
                        <el-text class="fullWid email" type="info">
                            {{ item.email }}
                        </el-text>
                    </div>
                </div>
                <el-button v-if="followStatus[item.useridAtten]" type="danger" plain
                    @click="toCancelAttenList(item)">添加关注</el-button>
                <!-- 暂时不需要在关注用户列表里加入关注 -->
                <!-- <el-button v-if="!followStatus[item.useridAtten]" type="success" plain
                    @click="toAdd(item)">加入关注</el-button> -->
            </div>
        </el-scrollbar>
        <!-- 用户列表 -->
        <el-scrollbar v-if="!listStatus" height="80%">
            <div class="userinfo" v-for="item in UserSearchedListData" :key="item.userid">
                <div>
                    <el-avatar :size="50" :src="item.userAvater" />
                    <div class="username-email">
                        <el-text class="fullWid username">
                            {{ item.username }}
                        </el-text>
                        <el-text class="fullWid email" type="info">
                            {{ item.email }}
                        </el-text>
                    </div>
                </div>
                <!-- 如果是初始化关注列表则传入useridAtten,如果是搜索用户列表则传入userid -->
                <el-button v-if="followStatus[item.userid]" type="danger" plain
                    @click="toCancelUserList(item)">取消关注</el-button>
                <el-button v-if="!followStatus[item.userid]" type="success" plain
                    @click="toAddUserList(item)">添加关注</el-button>
            </div>
        </el-scrollbar>
    </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { Search } from "@element-plus/icons-vue";
import request from '@/utils/request';
import store from "@/store";
import { ElMessage } from 'element-plus';

// 关注用户信息
interface userAtten {
    attenid: number,
    userid: number,
    username: string,
    email: string,
    useridAtten: number,
    userAvater: string,
}
// 用户信息
interface user {
    userid: number,
    username: string,
    email: string,
    rights: string,
    userAvater: string,
    isDeletedUser: number
}
// 关注用户信息列表
const FriendListData = ref<userAtten[]>()
// 搜索得出的用户信息列表
const UserSearchedListData = ref<user[]>()
// 博主们是否被当前用户关注
const followStatus = ref<Record<number, boolean>>({})
// 列表状态
// true 关注用户列表
// false 用户列表
const listStatus = ref<boolean>(true)
// 搜索框的值✨
const searchInputValue = ref<string>()
// 获取所有关注列表
const getAttention = async () => {
    listStatus.value = true;  // 切换为关注用户列表

    const userId = store.getters.getUser.userId;
    request.get('/attentionUser/queryAll', {
        params: {
            userid: userId
        }
    }).then(res => {
        FriendListData.value = res.data

        // 初始化是否被关注😭
        followStatus.value = {}
        // 由于是初始化被关注列表，所以必然是全关注
        // followStatus.value[userId] = true;
        for (const item of res.data) {
            followStatus.value[item.useridAtten] = true;
        }
    })
}
// 在全部用户中搜索目标博主
const getUserbyUsername = async () => {
    listStatus.value = false;  // 切换列表状态为用户列表

    request.get('/user/queryAll', {
        params: {
            username: searchInputValue.value
        }
    }).then(async res => {
        UserSearchedListData.value = res.data

        // 更新是否被关注😭
        followStatus.value = {}
        for (const item of res.data) {
            const isAtten = await queryIfAtten(item.userid);
            followStatus.value[item.userid] = isAtten;
        }
    })
}
// 当前博主是否被用户关注
const queryIfAtten = async (useridAtten: number): Promise<boolean> => {
    const userId = store.getters.getUser.userId;
    // 如果用户ID和被关注博主ID任一为空，假设它未被关注
    if (!userId || !useridAtten) {
        return false;
    }

    try {
        const res = await request.get('/attentionUser/queryIfAttention', {
            params: {
                userid: userId,
                useridAtten: useridAtten
            }
        });
        return res.data;  // 假设返回的结果是一个布尔值
    } catch (error) {
        console.error('请求失败', error);
        return false;  // 失败时返回 false
    }
}
// 关注用户列表：取消关注
const toCancelAttenList = async (item: userAtten) => {
    try {
        await request.delete('/attentionUser/delete', {
            params: {
                id: item.attenid
            }
        }).then(res => {
            console.log(res);
        })
        const res = await request.get('/fansUser/queryAll', {
            params: {
                userid: item.useridAtten,
                useridFans: item.userid
            }
        })
        await request.delete('/fansUser/delete', {
            params: {
                id: res.data[0].fansid
            }
        }).then(res => {
            console.log(res);

            ElMessage({
                message: '取消关注成功',
                type: 'success'
            })
        })
        getAttention()
    } catch (error) {
        ElMessage({
            message: '取消关注失败',
            type: 'error'
        })
    }

}
// 用户列表：取消关注
const toCancelUserList = async (item: user) => {
    const userId = store.getters.getUser.userId;

    try {
        const resAtten = await request.get('/attentionUser/queryAll', {
            params: {
                userid: userId,
                useridAtten: item.userid
            }
        })
        const resFans = await request.get('/fansUser/queryAll', {
            params: {
                userid: item.userid,
                useridFans: userId
            }
        })


        await request.delete('/attentionUser/delete', {
            params: {
                id: resAtten.data[0].attenid
            }
        }).then(res => {
            console.log(res);
        })

        await request.delete('/fansUser/delete', {
            params: {
                id: resFans.data[0].fansid
            }
        }).then(res => {
            console.log(res);

        })

        ElMessage({
            message: '取消关注成功',
            type: 'success'
        })
        getUserbyUsername()
    } catch (error) {
        ElMessage({
            message: '取消关注失败',
            type: 'error'
        })
    }
}
// 用户列表: 添加关注
const toAddUserList = async (item: user) => {
    const userId = store.getters.getUser.userId;  // 当前用户的ID

    try {
        await request.post('/attentionUser/add', {
            attenid: null,
            userid: userId,
            useridAtten: item.userid,
            username:item.username,
            email:item.email,
            userAvater:item.userAvater
        }).then(res => {
            console.log(res);
        })
        await request.post('/fansUser/add',{
            fansid:null,
            userid:item.userid,
            useridFans:userId,
            username:item.username,
            email:item.email,
            userAvater:item.userAvater
        }).then(res => {
            console.log(res);
            
        })

        ElMessage({
            message:'添加关注成功',
            type:'success'
        })

        getUserbyUsername()
    } catch (error) {
        ElMessage({
            message: '添加关注失败',
            type: 'error'
        })
    }


}
onMounted(
    () => {
        getAttention()
    }

)
</script>
<style lang="scss" scoped>
@use './BlogAttentionList.scss';
</style>
